
from dash import Output, Input, State, html
from models import Product, db, RepairRecord, MaintainRecord
from sqlalchemy import desc
from server import server
from modules.equipment.layouts import generate_equipment_detail

def register_callbacks(dash_app):
    # print("register equipment detail callback222222222222222")

    def get_equipment_maintain_and_repair_info(device_id):
        # 查询维护记录
        maintain_query = db.session.query(MaintainRecord).filter(
            MaintainRecord.product_id == device_id,
            MaintainRecord.is_active == True
        )
        maintain_count = maintain_query.count()
        last_maintain = maintain_query.order_by(desc(MaintainRecord.actual_date)).first()
        last_maintain_date = last_maintain.actual_date.strftime("%Y-%m-%d") if last_maintain and last_maintain.actual_date else "无"

        # 查询维修记录
        repair_count = db.session.query(RepairRecord).filter(
            RepairRecord.product_id == device_id,
            RepairRecord.is_active == True
        ).count()

        return last_maintain_date, maintain_count, repair_count

    # # 在设备详情回调中调用
    # last_maintain_date, maintain_count, repair_count = get_equipment_maintain_and_repair_info(device_id)
    # # 然后将这三个值填充到页面对应栏目

    # 设备详情展示（增强版）
    def register_equipment_detail_callback(dash_app):
        @dash_app.callback(
            Output('equipment-details', 'children'),
            [Input('equipment-table', 'selected_rows')],
            [State('equipment-table', 'data')]

        )
        def display_equipment_details(selected_rows, table_data):
            # print("--- display_equipment_details callback triggered ---") # Debug print
            if not selected_rows or not table_data:
                print("No row selected or table data is empty.") # Debug print
                return html.H4("请在左侧列表中选择一个设备查看详细信息", className="text-center text-muted mt-5")

            selected_row_index = selected_rows[0]
            selected_equipment = table_data[selected_row_index]
            # print(f"Selected row index: {selected_row_index}") # Debug print
            # print(f"Selected equipment data: {selected_equipment}") # Debug print

            product_id = selected_equipment.get('id')
            # print(f"Extracted product_id: {product_id}") # Debug print
            if not product_id:
                print(f"无法获取产品ID，可用的字段: {list(selected_equipment.keys())}")
                return html.H4("无法获取设备ID信息", className="text-center text-muted mt-5")

            with server.app_context():
                # print(f"Querying database for Product with id: {product_id}") # Debug print
                equipment = db.session.query(Product).filter(Product.id == product_id).first()
                # print(f"Database query result: {equipment}") # Debug print
                if not equipment:
                    print(f"Product with id {product_id} not found in database.") # Debug print
                    return html.H4("未找到设备信息", className="text-center text-muted mt-5")

                # Initialize fault_count before the query to prevent NameError
                fault_count = 0 # Add this line

                # 查询维护次数、上次维护日期
                maintain_query = db.session.query(MaintainRecord).filter(
                    MaintainRecord.product_id == product_id,
                    MaintainRecord.is_active == True
                )
                maintenance_count = maintain_query.count()
                last_maintain = maintain_query.order_by(desc(MaintainRecord.actual_date)).first()
                last_maintenance_date = last_maintain.actual_date.strftime('%Y-%m-%d') if last_maintain and last_maintain.actual_date else '无'

                # 查询故障次数
                try: # Add try-except block to catch potential errors during query
                    # print("Attempting to query fault count...") # Debug print
                    fault_count = db.session.query(RepairRecord).filter(
                        RepairRecord.product_id == product_id,
                        RepairRecord.is_active == True
                    ).count()
                    # print(f"Fault count queried successfully: {fault_count}") # Debug print
                except Exception as e:
                    print(f"Error querying fault count: {e}") # Debug print
                    # If an error occurs, fault_count remains 0 as initialized
                    pass # Continue execution even if query fails

                # Define status mapping
                # ...
                # Map running status code to Chinese description
                status_map = {
                    0: '正常',
                    1: '故障',
                    2: '维修中',
                    3: '报废',
                    # Add other status codes and their Chinese descriptions as needed
                }
                running_status_code = int(equipment.running_status)
                running_status_chinese = status_map.get(running_status_code, running_status_code if running_status_code is not None else '未知状态')
                # print(f"Mapped running status code {running_status_code} to Chinese description: {running_status_chinese}") # Debug print

                equipment_data = {
                    'product_id': equipment.id,
                    'product_code': equipment.product_code,
                    'name': equipment.product_name,
                    'category': equipment.equipment_category,
                    'type': equipment.equipment_type,
                    'brand': equipment.manufacturer,
                    'model': equipment.model,
                    'org_name': equipment.org_short_name_c,
                    'purchase_date': equipment.purchase_date.strftime('%Y-%m-%d') if equipment.purchase_date else '无',
                    'price': equipment.price,
                    # Use mapped Chinese status for the 'status' key (optional, depends on layout)
                    'status': running_status_chinese,
                    'software_version': equipment.software_version,
                    'hardware_version': equipment.hardware_version,
                    'network_address': equipment.network_address,
                    'service_life': equipment.service_life,
                    'technical_parameters': equipment.technical_parameters,
                    'manufacturer': equipment.manufacturer,
                    'manufacturer_country': equipment.manufacturer_country,
                    'production_date': equipment.production_date.strftime('%Y-%m-%d') if equipment.production_date else '无',
                    'factory_date': equipment.factory_date.strftime('%Y-%m-%d') if equipment.factory_date else '无',
                    'factory_representative': equipment.factory_representative,
                    'factory_contact_info': equipment.factory_contact_info,
                    # Use mapped Chinese status for the 'running_status' key (This is likely what the layout uses)
                    'running_status': running_status_chinese,
                    # 用最新维护数据覆盖原有字段
                    'last_maintenance_date': last_maintenance_date,
                    'maintenance_count': maintenance_count,
                    'fault_count': fault_count, # This line should now be safe
                    'next_maintenance_date': equipment.next_maintenance_date.strftime('%Y-%m-%d') if equipment.next_maintenance_date else '无',
                    # Removed 'completion_rate' field
                    # 'completion_rate': equipment.completion_rate
                }
                # print(f"Generated equipment_data dictionary: {equipment_data}") # Debug print
                return generate_equipment_detail(equipment_data)

    # 在 register_callbacks 函数内部调用嵌套的注册函数
    register_equipment_detail_callback(dash_app)
    